<template>
  <div class="query-form">
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      :label-width="labelWidth"
      class="query-form-content"
    >
      <!-- 查询条件区域 -->
      <div
        ref="queryFieldsRef"
        class="query-fields"
        :class="{ expanded: isExpanded }"
        :style="fieldsStyle"
      >
        <slot />
      </div>

      <!-- 按钮区域 -->
      <div class="query-actions" :class="buttonAlignment">
        <div class="action-buttons">
          <el-button type="primary" @click="handleQuery" :loading="loading">
            <el-icon><Icon icon="mdi:magnify" /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Icon icon="mdi:refresh" /></el-icon>
            重置
          </el-button>
        </div>

        <!-- 展开/收缩按钮 -->
        <div v-if="showExpandButton" class="expand-button">
          <el-button type="text" @click="toggleExpand">
            <el-icon><Icon :icon="isExpanded ? 'mdi:chevron-up' : 'mdi:chevron-down'" /></el-icon>
            {{ isExpanded ? '收起' : '展开' }}
          </el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUpdated } from 'vue'
import { ElForm, ElButton, ElIcon } from 'element-plus'
import { Icon } from '@iconify/vue'
import type { FormInstance } from 'element-plus'

interface Props {
  queryParams: Record<string, any>
  labelWidth?: string
  buttonAlignment?: 'left' | 'center' | 'right'
  maxRows?: number
  loading?: boolean
}

interface Emits {
  (e: 'query', params: Record<string, any>): void
  (e: 'reset'): void
  (e: 'update:queryParams', params: Record<string, any>): void
}

const props = withDefaults(defineProps<Props>(), {
  labelWidth: '80px',
  buttonAlignment: 'right',
  maxRows: 3,
  loading: false
})

const emit = defineEmits<Emits>()

const queryFormRef = ref<FormInstance>()
const queryFieldsRef = ref<HTMLElement>()
const isExpanded = ref(false)
const showExpandButton = ref(false)
const totalRows = ref(0)

// 计算字段样式
const fieldsStyle = computed(() => {
  if (!isExpanded.value && totalRows.value > props.maxRows) {
    return {
      maxHeight: `${props.maxRows * 60}px`,
      overflow: 'hidden'
    }
  }
  return {}
})

// 检测查询条件的行数
const detectRows = () => {
  nextTick(() => {
    if (queryFieldsRef.value) {
      const formItems = queryFieldsRef.value.querySelectorAll('.el-form-item')
      if (formItems.length > 0) {
        // 计算行数：每行3个，向上取整
        const calculatedRows = Math.ceil(formItems.length / 3)
        totalRows.value = calculatedRows

        // 如果行数超过最大行数，显示展开按钮
        showExpandButton.value = calculatedRows > props.maxRows

        // 如果当前是收缩状态且行数超过最大行数，重置为收缩状态
        if (!isExpanded.value && calculatedRows > props.maxRows) {
          isExpanded.value = false
        }
      }
    }
  })
}

// 切换展开/收缩状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}

// 处理查询
const handleQuery = () => {
  emit('query', props.queryParams)
}

// 处理重置
const handleReset = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  emit('reset')
}

// 重置表单
const resetForm = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
}

// 验证表单
const validateForm = async () => {
  if (queryFormRef.value) {
    return await queryFormRef.value.validate()
  }
  return true
}

// 获取表单实例
const getFormInstance = () => {
  return queryFormRef.value
}

// 暴露方法给父组件
defineExpose({
  resetForm,
  validateForm,
  getFormInstance,
  detectRows
})

// 监听插槽内容变化
onMounted(() => {
  detectRows()
})

onUpdated(() => {
  detectRows()
})

// 监听查询参数变化
watch(
  () => props.queryParams,
  () => {
    // 可以在这里添加逻辑，比如重置分页等
  },
  { deep: true }
)
</script>

<style lang="less" scoped>
.query-form {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;

  .query-form-content {
    .query-fields {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 16px;
      margin-bottom: 16px;
      transition: all 0.3s ease;
      position: relative;

      &.expanded {
        // 展开状态下的样式
      }

      // 响应式布局
      @media (max-width: 1200px) {
        grid-template-columns: repeat(2, 1fr);
      }

      @media (max-width: 768px) {
        grid-template-columns: 1fr;
      }
    }

    .query-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;

      &.left {
        justify-content: flex-start;
      }

      &.center {
        justify-content: center;
      }

      &.right {
        justify-content: flex-end;
      }

      .action-buttons {
        display: flex;
        gap: 8px;
      }

      .expand-button {
        .el-button {
          padding: 0;
          font-size: 12px;
          color: #409eff;
        }
      }
    }
  }
}

// 覆盖 Element Plus 的 inline 表单样式
:deep(.el-form--inline) {
  .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 100%;
  }
}

// 确保表单项在网格中正确显示
:deep(.el-form-item) {
  .el-form-item__content {
    width: 100%;

    .el-input,
    .el-select,
    .el-date-picker,
    .el-cascader {
      width: 100%;
    }
  }
}
</style>
